<template>  
    <div class="AddDailog">
        <el-form ref="form" :model="form" :rules="formRules" label-width="80px" :inline="true" size='medium'  @submit.native.prevent>
                    
                    <el-form-item label="耗材名称" prop="c_name" >
                        <el-input v-model="form.c_name" placeholder="请输入耗材名称" maxlength="20"></el-input>
                    </el-form-item>
                    <el-form-item label="耗材编码" prop="c_code" >
                        <el-input v-model="form.c_code" placeholder="请输入耗材名称" maxlength="20"></el-input>
                    </el-form-item>
                    <el-form-item label="耗材分类" prop="c_cid" >
                        <el-select v-model="form.c_cid" placeholder="请输入耗材类别" >
                            <el-option-group v-for="group in classOption" :key="group.id" :label="group.category_name">
                                <el-option v-for="item in group.cate" :key="item.id" :label="item.category_name" :value="item.id">
                                </el-option>
                            </el-option-group>
                        </el-select>
                    </el-form-item>
                      <el-form-item label="计量单位" prop="c_unit">
                        <el-input v-model="form.c_unit" placeholder="请输入单位" maxlength="10"></el-input>
                    </el-form-item>
                    <el-form-item label="选择仓库" prop="wh_id">
                        <el-select  v-model="form.wh_id" disabled placeholder="请选择仓库">
                            <el-option v-for="item in warehouseOptions"  :key="item.wh_id" :label="item.wh_name" :value="item.wh_id" ></el-option>
                        </el-select>
                    </el-form-item>
                     <el-form-item label="单价" prop="c_unit_price">
                        <el-input v-model="form.c_unit_price" placeholder="请输入金额" maxlength="10" ></el-input>
                    </el-form-item>
                    <el-form-item label="供应商" prop="c_supplier">
                        <el-input v-model="form.c_supplier" placeholder="请输入供应商" maxlength="10" ></el-input>
                    </el-form-item>

                    <el-form-item label="品牌名称" prop="c_brand">
                        <el-input v-model="form.c_brand" placeholder="请输入耗材品牌" maxlength="20"></el-input>
                    </el-form-item>
                    <el-form-item label="采购时间" prop="c_purchase_date">
                        <el-date-picker type="date" value-format="yyyy-MM-dd" placeholder="请选择采购时间" v-model="form.c_purchase_date" ></el-date-picker>
                    </el-form-item>

                    <el-form-item label="入库时间" prop="c_storage_date">
                        <el-date-picker type="date" value-format="yyyy-MM-dd" placeholder="请选择入库时间" v-model="form.c_storage_date "  ></el-date-picker>
                    </el-form-item>
                     <el-form-item label="规格型号" prop="c_specs">
                        <el-input v-model="form.c_specs" placeholder="请输入耗材型号" maxlength="20"></el-input>
                    </el-form-item>
                    <el-form-item label="入库数量" prop="c_stock"> 
                        <el-input v-model.number="form.c_stock" placeholder="请输入入库数量" maxlength="20"></el-input>
                    </el-form-item>  
                     <el-form-item label="库存下限" prop="c_stock_limit">
                        <el-input v-model.number="form.c_stock_limit" placeholder="请输入使用年限" maxlength="20"></el-input>
                    </el-form-item>
                      <el-form-item label="采购人"  prop="c_purchase_name">
                            <el-input v-model="form.c_purchase_name" placeholder="请输入采购人" maxlength="20"></el-input>
                    </el-form-item>
                    <div>
                        <el-form-item label="图片" prop="c_image_url">
                           <ul class="mainlist">
                                <li v-for="(list,index) in form.c_image_url" :key="index" @mouseenter="list.delshow=true"  @mouseleave="list.delshow=false" >
                                    <img class="img" :src="list.image_url" alt="" width="70px" height="70px">
                                    <div class="delpic" v-if="list.delshow" >
                                        <i @click.stop="delcouPicHan(list,index)" class="el-icon-delete ii"></i> 
                                        <i @click.stop="dialogImageUrl=list.image_url;dialogVisible=true;" class="el-icon-zoom-in ii"></i> 
                                    </div>
                                </li>
                                <li  @click.stop="upcouPic(2)" v-loading.fullscreen.lock="fullscreenLoading">
                                        <!-- <span style="font-size:50px;color:rgb(217,217,217)">+</span>     -->
                                         <i style="font-size:40px;color:rgb(217,217,217);font-weight:600" class="el-icon-plus"></i>
                                </li>
                            </ul>
                            <div class="tip">图片尺寸为正方形，最多上传6张，只支持.jpg 格式。</div>
                        </el-form-item>
                    </div>
                    <el-form-item >
                        <el-button style="margin-left:80px" type="primary" @click="onSubmit">保存</el-button>
                        <el-button @click="reset">重置</el-button>
                    </el-form-item>
        </el-form>
        <!-- 图片预览 -->
        <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
    </div>
</template>

<script>
 /* eslint-disable */ 
import fileUtil from '@/libs/fileUtil.js'
import moment from 'moment'
import OSS from 'ali-oss'
import {getCategoriesApi,getRam } from "@/api" 
import {createConsumable,getConsumablesDetail,updateConsumables} from "../api" 
export default {
    name:"formvue",
    props: ['edit'],
    data(){
        /**数字验证 */
        var checkNumber = (rule, value, callback)=>{
            if (!value) {
                return callback(new Error('使用年限必须大于零'));
            } else {
                const reg = /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/
                if (reg.test(value)) {
                    callback();
                } else {
                    return callback(new Error('请输入大于0的数字'));
                }
            }
        };
        return{
            fullscreenLoading:false,
            dialogVisible:false,/**显示预览图片 */
            dialogImageUrl:'',/**预览图片url */
            warehouseOptions:[],/**所有仓库 */
            classOption:[],/**所有分类 */
            form:{
                c_image_url:[],
                c_name:'',
                c_code:'',
                c_unit:'',
                c_cid:'',
                wh_id:'',
                c_brand:'',
                c_unit_price:'',
                c_stock:'',
                c_stock_limit:'',
                c_supplier:'',
                c_purchase_date:'',
                c_purchase_name:'',
                c_specs:'',
            },
            formRules: {
                c_name: [ { required: true, message: '耗材名称不能为空', trigger: 'blur' }],/*耗材名称的校验*/
                c_code:[ { required: true, message: '耗材编码不能为空', trigger: 'blur' }],/*耗材名称的校验*/
                c_unit:[ { required: true, message: '计量单位不能为空', trigger: 'blur' }],/*耗材名称的校验*/
                c_cid: [{ required: true, message: '请选择耗材类别', trigger: 'blur' }],/*耗材类别的校验*/
                wh_id: [{ required: true, message: '请选择仓库', trigger: 'blur' }],/*仓库的的校验*/
                c_unit: [{ required: true, message: '单位不能为空', trigger: 'blur' }],/*单位的校验*/
                // c_specs:[{ required: true, message: '规格型号不能为空', trigger: 'blur' }],/*规格型号的校验*/
                // c_brand:[{ required: true, message: '品牌名称不能为空', trigger: 'blur' }],/*耗材名称的校验*/
                c_stock:[ { required: true, message: '入库数量不能为空', trigger: 'blur' }],/*入库数量的校验*/
                // c_purchase_name:[ { required: true, message: '采购人不能为空', trigger: 'blur' }],/*采购人的校验*/
                c_stock_limit: [{ type: 'number', required: true, message: '请输入库存下限', trigger: 'blur' }],/*保修年限的校验*/
                // c_image_url:[{ type: 'array', required: true, message: '请上传图片', trigger: 'change' }],/*保修年限的校验*/
            },
        }
    },
    created(){
        this.getClassData()
        if(this.$route.query.id){
            getConsumablesDetail({id:this.$route.query.id}).then(res=>{
                res.image&&res.image.length?res.image.forEach(element => {
                    element.delshow = false
                }):''
                this.form = {
                    c_image_url:res.image,
                    c_stock:res.c_stock,
                    c_cid:res.c_cid,
                    c_name:res.c_name,
                    c_code:res.c_code,
                    c_supplier:res.c_supplier,
                    c_unit:res.c_unit,
                    wh_id:res.wh_id,
                    c_specs:res.c_specs,
                    c_brand:res.c_brand,
                    c_unit_price:res.c_unit_price,
                    c_num:res.c_num,
                    c_purchase_name:res.c_purchase_name,
                    c_stock_limit:res.c_stock_limit,
                    c_purchase_date:res.c_purchase_date,
                    c_storage_date:res.c_storage_date,
                }
            })
        }
    },
    methods: {
        /**获取全部资产分类 */
        getClassData(){
            this.warehouseOptions = this.$store.state.myWarehouse
            log(this.warehouseOptions,this.$store.state.warehouseOfAssetsManager)
            this.form.wh_id = this.$store.state.warehouseOfAssetsManager
            this.form.c_cid = ''
            getCategoriesApi({category_type:1,wh_id:this.$store.state.warehouseOfAssetsManager}).then(res=>{
                this.classOption = res
            })
        },
        /**创建新资产 */
        onSubmit(){
            log(this.form)
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    let params = JSON.parse(JSON.stringify(this.form))
                    params.c_image_url = JSON.stringify(params.c_image_url)
                   if(this.$route.query.id){
                       params.id = this.$route.query.id
                       updateConsumables(params).then(res=>{
                           let that = this
                           setTimeout(()=>{
                               that.$router.go(-1)
                           },1000)
                       })
                   }else{
                       createConsumable(params).then(res=>{
                           this.$refs['form'].resetFields();
                       })
                   }

                }
            });
        },
         //删除图片
        delcouPicHan(list,index){
            this.form.c_image_url.splice(index, 1)
        },
          //图片上传
        upcouPic(val){
            if(this.form.c_image_url.length<6){
                fileUtil.getFile({
                    multiple:true,
                    aaccept:"image/jpg,image/png", //文件类型， 非必填，默认值image/*
                    done:(files,src,dom)=>{
                        var file = Array.prototype.slice.call(files) 
                        let _this =this;
                        getRam().then(res=>{
                            var client = new OSS({
                                region: res.region,
                                accessKeyId: res.accessKeyId,
                                accessKeySecret: res.accessKeySecret,
                                bucket:  res.bucket
                            });
                            let arr = []
                            for(let i=0;i<file.length;i++){ /**循环上传 */
                                if(this.form.c_image_url.length+i<6){
                                    this.fullscreenLoading = true
                                    if(file[i].type.indexOf('image')>-1){
                                        let promise = client.multipartUpload((new Date().getTime())+file[i].name, file[i]).then(function(respond){
                                        let obj = {image_url:res.url+respond.name,delshow:false}
                                        _this.form.c_image_url.push(obj)
                                        }).catch((err) => {
                                            log(2222,err)
                                        })
                                        arr.push(promise)
                                    }else{
                                    return Toast('文件格式不对');
                                    }
                                }else{
                                    this.$message.warning(`当前限制选择 6 个文件，请将不要的附件先进行删除`);
                                }
                            }
                            Promise.all(arr).then((result) => {
                                this.fullscreenLoading = false
                            }).catch(err=>{
                                this.fullscreenLoading = false
                            })
                        })
                    }
                })
            }else{
                this.$message.warning(`当前限制选择 6 个文件，请将不要的附件先进行删除`);
            }
        },
        /**重置 */
        reset(){
            this.$refs['form'].resetFields();
        }
    },
}
</script>

<style lang="stylus" scoped>
.AddDailog
    background-color #FFFFFF
    padding 32px 40px 58px 40px
    .mainlist
        display: flex
        li
            width 70px
            position relative
            height 70px
            cursor pointer
            margin 10px 10px 10px 0
        li:last-child 
            width 64px
            height 64px
            display flex
            align-items center
            justify-content center
            border 3px  dashed  rgb(217,217,217)
        .delpic
            height 70px;
            background rgba(0,0,0,0.5)
            position absolute
            display flex
            justify-content space-around
            align-items center
            right 0
            bottom 0
            z-index 100
            width: 70px;
            line-height 64px
            color #fff
            font-size 30px
    .tip
        color #A6A3A3
        font-size 12px
        >span 
            color rgb(237,80,90)
            font-size 12px

               
</style>
<style lang="stylus">
.AddDailog
    // .el-select>.el-input
    //     width 206.4px
    // .el-date-editor.el-input, .el-date-editor.el-input__inner
    //     width 206.4px
    .el-input--medium
        width 206.4px
</style>
